package org.belkodevelop.controller;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.belkodevelop.auth.dto.RecoveryPasswordStatus;
import org.belkodevelop.controller.helper.AuthUtils;
import org.belkodevelop.token.service.TokenService;
import org.belkodevelop.user.exception.ErrorSendMail;
import org.belkodevelop.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

@Controller
public class PasswordRecoveryController {
    private final Log log = LogFactory.getLog(getClass());
    
    @Autowired
    private AuthUtils authUtils;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private TokenService tokenService;    

    @RequestMapping(method = RequestMethod.GET, value = "/password_recovery.html")
    public ModelAndView index() {
        return new ModelAndView("password_recovery");
    }
    
    @RequestMapping(method = RequestMethod.POST, value = "/api/recovery_password/send_email.json")
    @ResponseBody
    public RecoveryPasswordStatus sendEmail(@RequestParam String email) {
        try {
            userService.sendRecoveryPasswordMail(email);
        } catch (Exception ex) {
            log.warn("Error sending emails", ex);
            return new RecoveryPasswordStatus(true);
        }
        return new RecoveryPasswordStatus(false);
    }    

    @RequestMapping(method = RequestMethod.GET, value = "/password_recovery/in.html")
    public String indexForceLogin(@RequestParam String login, @RequestParam String token) {
        if (userService.checkRecoveryPasswordToken(login, token)) {
            if (authUtils.forceLogin(login)) {
                tokenService.removeToken(token);
                return "redirect:new_password.html";
            }
        }
        return null;
    }
    
    @RequestMapping(method = RequestMethod.GET, value = "/password_recovery/new_password.html")
    public ModelAndView indexNewPassword() {
        return new ModelAndView("change_password");
    }
    
    @RequestMapping(method = RequestMethod.POST, value = "/api/password_recovery/new_password.json")
    @ResponseBody
    public RecoveryPasswordStatus postChangePassword(@RequestParam String password, @RequestParam String confirmPassword) {
        try {
            userService.changePassword(authUtils.getCurrentUser().getId(), password);
        } catch(Exception ex) {
            log.error("Error changing password", ex);
            return new RecoveryPasswordStatus(true);
        }
        return new RecoveryPasswordStatus(false);
    }

}
